import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import homeUrl from '/public/home.png'
import { useWidthUserHooks } from '@/stores/user'
import axios from 'axios'

// 这里是路由的知识点
export const router_menus: RouteRecordRaw[] = [
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/home/indexView.vue'),
    meta: {
      icon: homeUrl,
      title: '精品推荐'
    }
  },
  {
    path: '/a',
    name: 'a',
    component: () => import('@/views/home/indexView.vue'),
    meta: {
      icon: homeUrl,
      title: '精品推荐'
    }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login/indexView.vue')
    },
    {
      path: '/create/product/:id?',
      name: 'CreateProduct',
      component: () => import('@/views/createProduct/indexView.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/register/indexView.vue'),
      children: router_menus
    },
    {
      path: '/',
      name: 'layout',
      redirect: '/home',
      component: () => import('@/layout/indexView.vue'),
      children: router_menus
    },
    {
      path: '/public/product',
      name: 'publicProduct',
      component: () => import('@/views/publicProduct/indexView.vue')
    },
    {
      path: '/product/list',
      name: 'ProductList',
      component: () => import('@/views/productList/indexView.vue')
    },
    {
      path: '/public/:id',
      name: 'PublicView',
      component: () => import('@/views/publicView/indexView.vue')
    }
  ]
})

router.beforeEach(async (to, from, next) => {
  // const token = localStorage.getItem('token')
  const { userInfo, setUserInfo, QuitLogin, token } = useWidthUserHooks()
  const whiteList = ['/login', '/register']
  if (token) {
    if (userInfo && !userInfo.id) {
      try {
        const resp = await axios.get('/user/info')
        const { code } = resp.data
        if (code === 200) {
          setUserInfo(resp.data.data)
          next({ ...to, replace: true })
        } else {
          next()
        }
      } catch {
        QuitLogin()
        next('/login')
      }
    } else if (whiteList.includes(to.path)) {
      return next('/')
    } else {
      return next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      return next()
    } else {
      return next({ path: '/login' })
    }
  }
})

console.log(11111111111111)
export default router
